/**
 * 背景脚本
 * 
 * 控制背景颜色的改变
 * 背景星星的展示
 */

cc.Class({
  extends: cc.Component,

  properties: {
    star: cc.Prefab,
    time: 0,
  },

  onLoad() {
    var that = this;
    cc.game.addPersistRootNode(this.node.parent); // 将背景node设为常驻节点
    this.node.parent.zIndex = -9999;
    // 循环生成星星
    for (var i = 0; i < 13; i++) {
      var randTime = Math.random() * 4000;
      setTimeout(function () {
        for (var j = 0; j < 4; j++) {
          that.showStar();
        }
      }, randTime);
    }
  },

  // 通过时间控制背景颜色改变
  update(dt) {
    this.time += dt;
    var _time = parseInt(this.time)
    if (_time > 0 && _time % 20 == 0) {
      var r = Math.ceil(Math.random() * 100 + 45);
      var g = Math.ceil(Math.random() * 100 + 66);
      var b = Math.ceil(Math.random() * 77 + 88);
      var action = cc.tintTo(2, r, g, b);
      this.node.runAction(action)
    }
  },

  // 随机位置生成星星
  showStar: function () {
    var star = cc.instantiate(this.star);
    this.node.addChild(star);
    var randX = Math.random() * 1000 - 500;
    var randY = Math.random() * 1800 - 900;
    star.setPosition(cc.v2(randX, randY));
  }
});
